import React, { useState, useEffect, useCallback } from 'react';
import {
  PlusCircle,
  Copy,
  Heart,
  Trash2,
  RefreshCw,
  FileText,
  TrendingUp,
  Clock,
  Users,
  ChevronDown,
} from 'lucide-react';
import { textGenerationApi, aiProviderApi, enhancedTextGenerationApi } from '../api';
import type {
  TextGenerationRequest,
  TextGenerationResponse,
  TextGenerationHistory,
  TextGenerationStats,
  TextTemplate,
  AIProvider,
  EnhancedTextGenerationRequest,
  ContentType,
  WritingTone,
  SocialPlatform,
  CreateSocialAccountRequest,
} from '../api/types';
import { useApiError } from '../hooks/useApiError';
import { useSocialAccountStore, useActiveAccount } from '../stores/socialAccountStore';

const TextGeneration: React.FC = () => {
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedContent, setGeneratedContent] = useState<TextGenerationResponse | null>(null);
  const [history, setHistory] = useState<TextGenerationHistory[]>([]);
  const [stats, setStats] = useState<TextGenerationStats | null>(null);
  const [templates, setTemplates] = useState<TextTemplate[]>([]);
  const [activeTab, setActiveTab] = useState<'generate' | 'history' | 'templates'>('generate');

  // AI Provider and Model state
  const [providers, setProviders] = useState<AIProvider[]>([]);
  const [availableModels, setAvailableModels] = useState<string[]>([]);
  const [loadingModels, setLoadingModels] = useState(false);

  // Social Account Integration
  const activeAccount = useActiveAccount();
  const { accounts, loadAccounts, activateAccount, createAccount } = useSocialAccountStore();
  const [showAccountSelector, setShowAccountSelector] = useState(false);
  const [showCreateAccountModal, setShowCreateAccountModal] = useState(false);
  const [createAccountForm, setCreateAccountForm] = useState<CreateSocialAccountRequest>({
    name: '',
    platform: 'weibo',
    description: '',
  });

  // Enhanced form state with account context support
  const [formData, setFormData] = useState<EnhancedTextGenerationRequest>({
    type: 'marketing' as ContentType,
    topic: '',
    audience: '',
    tone: 'professional' as WritingTone,
    length: 'medium',
    language: 'zh-CN',
    requirements: '',
    account_id: activeAccount?.id,
    use_account_memory: true,
    apply_brand_voice: true,
    follow_guidelines: true,
  });

  // Filters
  const [historyFilter, setHistoryFilter] = useState({
    search: '',
    type: '',
    favorites: false,
  });

  const { handleError } = useApiError();

  // Sync formData.account_id with activeAccount
  useEffect(() => {
    setFormData(prev => ({ ...prev, account_id: activeAccount?.id }));
  }, [activeAccount?.id]);

  // Load accounts on component mount
  useEffect(() => {
    loadAccounts();
  }, [loadAccounts]);

  // Close account selector when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (showAccountSelector) {
        const target = event.target as HTMLElement;
        if (!target.closest('[data-account-selector]')) {
          setShowAccountSelector(false);
        }
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [showAccountSelector]);

  const loadStats = useCallback(async () => {
    try {
      const response = await textGenerationApi.getStats();
      setStats(response);
    } catch (error) {
      handleError(error, '获取统计数据失败');
    }
  }, [handleError]);

  const loadHistory = useCallback(async () => {
    try {
      const response = await textGenerationApi.getHistory({ limit: 20 });
      setHistory(response.rows || []);
    } catch (error) {
      handleError(error, '获取历史记录失败');
    }
  }, [handleError]);

  const loadTemplates = useCallback(async () => {
    try {
      const response = await textGenerationApi.getTemplates({ is_active: true });
      setTemplates(response.rows || []);
    } catch (error) {
      handleError(error, '获取模板失败');
    }
  }, [handleError]);

  const loadModels = useCallback(
    async (providerId: number) => {
      try {
        setLoadingModels(true);
        const models = await textGenerationApi.getProviderModels(providerId);
        setAvailableModels(models);

        // Set default model if available
        if (models.length > 0 && !formData.model) {
          setFormData(prev => ({ ...prev, model: models[0] }));
        }
      } catch (error) {
        handleError(error, '获取模型列表失败');
      } finally {
        setLoadingModels(false);
      }
    },
    [handleError, formData.model]
  );

  const loadProviders = useCallback(async () => {
    try {
      const response = await aiProviderApi.list();
      const activeProviders = response.rows?.filter(p => p.status === 'active') || [];
      setProviders(activeProviders);

      // Set default provider if available
      if (activeProviders.length > 0 && !formData.provider_id) {
        const defaultProvider = activeProviders.find(p => p.is_active) || activeProviders[0];
        setFormData(prev => ({ ...prev, provider_id: defaultProvider.id }));
      }
    } catch (error) {
      handleError(error, '获取AI服务提供商失败');
    }
  }, [handleError, formData.provider_id]);

  // Load data
  useEffect(() => {
    loadStats();
    loadProviders();
    if (activeTab === 'history') {
      loadHistory();
    } else if (activeTab === 'templates') {
      loadTemplates();
    }
  }, [activeTab, loadStats, loadHistory, loadTemplates, loadProviders]);

  // Load models when provider changes
  useEffect(() => {
    if (formData.provider_id) {
      loadModels(formData.provider_id);
    }
  }, [formData.provider_id, loadModels]);

  const handleProviderChange = (providerId: number) => {
    setFormData(prev => ({ ...prev, provider_id: providerId, model: undefined }));
    setAvailableModels([]);
    loadModels(providerId);
  };

  const handleGenerate = async () => {
    if (!formData.topic.trim()) {
      alert('请输入主题或关键词');
      return;
    }

    if (!formData.provider_id) {
      alert('请选择AI服务商');
      return;
    }

    if (!formData.model) {
      alert('请选择模型');
      return;
    }

    setIsGenerating(true);
    try {
      // 使用增强版API，支持账号上下文
      const response =
        formData.account_id && formData.use_account_memory
          ? await enhancedTextGenerationApi.generateWithAccount(formData)
          : await textGenerationApi.generate(formData as TextGenerationRequest);

      setGeneratedContent(response);
      loadStats(); // Refresh stats
    } catch (error) {
      handleError(error, '文案生成失败');
    } finally {
      setIsGenerating(false);
    }
  };

  const handleCopyContent = (content: string) => {
    navigator.clipboard.writeText(content);
    // Show toast notification
  };

  const handleToggleFavorite = async (id: string) => {
    try {
      await textGenerationApi.toggleFavorite(id);
      loadHistory(); // Refresh history
    } catch (error) {
      handleError(error, '操作失败');
    }
  };

  const handleDeleteHistory = async (id: string) => {
    if (confirm('确定要删除这条记录吗？')) {
      try {
        await textGenerationApi.deleteHistory(id);
        loadHistory(); // Refresh history
      } catch (error) {
        handleError(error, '删除失败');
      }
    }
  };

  const handleCreateAccount = async () => {
    if (!createAccountForm.name.trim()) {
      alert('请输入账号名称');
      return;
    }

    try {
      await createAccount(createAccountForm);
      setShowCreateAccountModal(false);
      setCreateAccountForm({ name: '', platform: 'weibo', description: '' });
      setShowAccountSelector(false);
    } catch (error) {
      handleError(error, '创建账号失败');
    }
  };

  const platformOptions: Array<{ value: SocialPlatform; label: string }> = [
    { value: 'weibo', label: '微博' },
    { value: 'wechat', label: '微信公众号' },
    { value: 'douyin', label: '抖音' },
    { value: 'xiaohongshu', label: '小红书' },
    { value: 'zhihu', label: '知乎' },
    { value: 'bilibili', label: 'B站' },
    { value: 'toutiao', label: '今日头条' },
    { value: 'baidu', label: '百家号' },
    { value: 'other', label: '其他' },
  ];

  const renderAccountSelector = () => (
    <div className="bg-gray-900 border border-gray-800 rounded-xl p-4 mb-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <div className="flex items-center space-x-2">
            <Users className="w-5 h-5 text-blue-400" />
            <span className="text-sm font-medium text-gray-300">当前账号:</span>
          </div>

          <div className="relative" data-account-selector>
            <button
              onClick={() => setShowAccountSelector(!showAccountSelector)}
              className="cursor-pointer flex items-center space-x-2 px-3 py-1.5 bg-gray-800 hover:bg-gray-700 border border-gray-600 rounded-lg text-gray-100 transition-colors"
            >
              {activeAccount ? (
                <>
                  <div className="w-2 h-2 rounded-full bg-green-400"></div>
                  <span className="font-medium">{activeAccount.name}</span>
                  <span className="text-xs text-gray-400 bg-gray-700 px-2 py-0.5 rounded">
                    {activeAccount.platform}
                  </span>
                </>
              ) : (
                <span className="text-gray-400">未选择账号</span>
              )}
              <ChevronDown className="w-4 h-4 text-gray-400" />
            </button>

            {/* Account Dropdown */}
            {showAccountSelector && (
              <div className="absolute top-full left-0 mt-1 w-64 bg-gray-800 border border-gray-600 rounded-lg shadow-xl z-10">
                <div className="p-2">
                  <div className="text-xs text-gray-400 px-2 py-1">选择自媒体账号</div>
                  {accounts.length > 0 ? (
                    accounts.map(account => (
                      <button
                        key={account.id}
                        onClick={() => {
                          activateAccount(account.id);
                          setShowAccountSelector(false);
                        }}
                        className={`cursor-pointer w-full flex items-center space-x-3 px-3 py-2 rounded-lg text-left transition-colors ${
                          activeAccount?.id === account.id
                            ? 'bg-blue-600 text-white'
                            : 'text-gray-300 hover:bg-gray-700'
                        }`}
                      >
                        <div
                          className={`w-2 h-2 rounded-full ${
                            account.is_active ? 'bg-green-400' : 'bg-gray-500'
                          }`}
                        ></div>
                        <div className="flex-1">
                          <div className="font-medium">{account.name}</div>
                          <div className="text-xs opacity-75">{account.platform}</div>
                        </div>
                      </button>
                    ))
                  ) : (
                    <div className="px-3 py-2 text-sm text-gray-400">暂无可用账号</div>
                  )}
                </div>
                <div className="border-t border-gray-600 p-2">
                  <button
                    onClick={() => {
                      setShowCreateAccountModal(true);
                      setShowAccountSelector(false);
                    }}
                    className="cursor-pointer w-full text-sm text-blue-400 hover:text-blue-300 px-2 py-1 text-left"
                  >
                    + 添加新账号
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Account Context Controls */}
        {activeAccount && (
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                id="use_account_memory"
                checked={formData.use_account_memory}
                onChange={e =>
                  setFormData(prev => ({ ...prev, use_account_memory: e.target.checked }))
                }
                className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
              />
              <label htmlFor="use_account_memory" className="text-sm text-gray-300">
                使用账号记忆
              </label>
            </div>
            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                id="apply_brand_voice"
                checked={formData.apply_brand_voice}
                onChange={e =>
                  setFormData(prev => ({ ...prev, apply_brand_voice: e.target.checked }))
                }
                className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
              />
              <label htmlFor="apply_brand_voice" className="text-sm text-gray-300">
                应用品牌语调
              </label>
            </div>
            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                id="follow_guidelines"
                checked={formData.follow_guidelines}
                onChange={e =>
                  setFormData(prev => ({ ...prev, follow_guidelines: e.target.checked }))
                }
                className="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
              />
              <label htmlFor="follow_guidelines" className="text-sm text-gray-300">
                遵循品牌指导原则
              </label>
            </div>
          </div>
        )}
      </div>
    </div>
  );

  const renderGenerateTab = () => (
    <div className="space-y-6">
      {/* Account Selector */}
      {renderAccountSelector()}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Form Section */}
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
          <h2 className="text-xl font-semibold text-gray-100 mb-6">创建文案</h2>

          <div className="space-y-4">
            {/* Type Selection */}
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">文案类型</label>
              <select
                value={formData.type}
                onChange={e => setFormData({ ...formData, type: e.target.value as ContentType })}
                className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="marketing">营销文案</option>
                <option value="product_desc">产品描述</option>
                <option value="social_post">社交媒体帖子</option>
                <option value="article">长文章</option>
                <option value="short_text">短文案</option>
                <option value="video_script">视频脚本</option>
              </select>
            </div>

            {/* Topic */}
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">主题/关键词</label>
              <input
                type="text"
                value={formData.topic}
                onChange={e => setFormData({ ...formData, topic: e.target.value })}
                placeholder="请输入产品或服务的主题"
                className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            {/* Audience */}
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">目标受众</label>
              <input
                type="text"
                value={formData.audience}
                onChange={e => setFormData({ ...formData, audience: e.target.value })}
                placeholder="例如：年轻女性、企业主、科技爱好者"
                className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            {/* AI Provider and Model Selection */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">AI服务商</label>
                <select
                  value={formData.provider_id || ''}
                  onChange={e => handleProviderChange(Number(e.target.value))}
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">选择服务商</option>
                  {providers.map(provider => (
                    <option key={provider.id} value={provider.id}>
                      {provider.name} ({provider.provider_type.toUpperCase()})
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">模型</label>
                <select
                  value={formData.model || ''}
                  onChange={e => setFormData(prev => ({ ...prev, model: e.target.value }))}
                  disabled={loadingModels || availableModels.length === 0}
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
                >
                  {loadingModels ? (
                    <option value="">加载中...</option>
                  ) : availableModels.length === 0 ? (
                    <option value="">暂无可用模型</option>
                  ) : (
                    <>
                      <option value="">选择模型</option>
                      {availableModels.map(model => (
                        <option key={model} value={model}>
                          {model}
                        </option>
                      ))}
                    </>
                  )}
                </select>
              </div>
            </div>

            {/* Tone and Length */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">语调风格</label>
                <select
                  value={formData.tone}
                  onChange={e =>
                    setFormData({
                      ...formData,
                      tone: e.target.value as WritingTone,
                    })
                  }
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="professional">专业</option>
                  <option value="casual">轻松</option>
                  <option value="friendly">友好</option>
                  <option value="humorous">幽默</option>
                  <option value="authoritative">权威</option>
                  <option value="emotional">感性</option>
                  <option value="minimalist">简约</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">文案长度</label>
                <select
                  value={formData.length}
                  onChange={e =>
                    setFormData({
                      ...formData,
                      length: e.target.value as TextGenerationRequest['length'],
                    })
                  }
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="short">简短</option>
                  <option value="medium">中等</option>
                  <option value="long">详细</option>
                </select>
              </div>
            </div>

            {/* Language */}
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">语言</label>
              <select
                value={formData.language}
                onChange={e =>
                  setFormData({
                    ...formData,
                    language: e.target.value,
                  })
                }
                className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="zh-CN">中文</option>
                <option value="en-US">English</option>
                <option value="ja-JP">日本語</option>
                <option value="ko-KR">한국어</option>
              </select>
            </div>

            {/* Requirements */}
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">附加要求</label>
              <textarea
                value={formData.requirements}
                onChange={e => setFormData({ ...formData, requirements: e.target.value })}
                placeholder="其他特殊要求或注意事项..."
                rows={3}
                className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              />
            </div>

            {/* Generate Button */}
            <button
              onClick={handleGenerate}
              disabled={isGenerating || !formData.topic.trim()}
              className="w-full flex items-center justify-center px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isGenerating ? (
                <>
                  <RefreshCw className="animate-spin w-4 h-4 mr-2" />
                  生成中...
                </>
              ) : (
                <>
                  <PlusCircle className="w-4 h-4 mr-2" />
                  生成文案
                </>
              )}
            </button>
          </div>
        </div>

        {/* Result Section */}
        <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-semibold text-gray-100">生成结果</h2>
            {generatedContent && (
              <button
                onClick={() => handleCopyContent(generatedContent.content)}
                className="flex items-center px-4 py-2 bg-gray-700 hover:bg-gray-600 text-gray-200 rounded-lg transition-colors"
              >
                <Copy className="w-4 h-4 mr-2" />
                复制
              </button>
            )}
          </div>

          {isGenerating ? (
            <div className="flex items-center justify-center h-64">
              <div className="text-center">
                <RefreshCw className="animate-spin w-8 h-8 text-blue-500 mx-auto mb-4" />
                <p className="text-gray-400">正在生成文案，请稍候...</p>
              </div>
            </div>
          ) : generatedContent ? (
            <div className="space-y-4">
              <div className="p-4 bg-gray-800 rounded-lg">
                <div className="text-sm text-gray-400 mb-2">
                  {generatedContent.type} • {generatedContent.word_count} 字 •{' '}
                  {generatedContent.created_at}
                </div>
                <div className="text-gray-100 leading-relaxed whitespace-pre-wrap">
                  {generatedContent.content}
                </div>
              </div>

              <div className="flex items-center justify-between text-sm text-gray-500">
                <span>主题: {generatedContent.topic}</span>
                {generatedContent.model && <span>模型: {generatedContent.model}</span>}
              </div>
            </div>
          ) : (
            <div className="flex items-center justify-center h-64">
              <div className="text-center">
                <FileText className="w-12 h-12 text-gray-600 mx-auto mb-4" />
                <p className="text-gray-500">输入信息并点击生成按钮来创建文案</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );

  const renderHistoryTab = () => (
    <div className="space-y-6">
      {/* Filters */}
      <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <input
              type="text"
              placeholder="搜索文案..."
              value={historyFilter.search}
              onChange={e => setHistoryFilter({ ...historyFilter, search: e.target.value })}
              className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
          <div>
            <select
              value={historyFilter.type}
              onChange={e => setHistoryFilter({ ...historyFilter, type: e.target.value })}
              className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="">所有类型</option>
              <option value="marketing">营销推广</option>
              <option value="product">产品介绍</option>
              <option value="social">社交媒体</option>
              <option value="creative">创意文案</option>
              <option value="custom">自定义</option>
            </select>
          </div>
          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={historyFilter.favorites}
                onChange={e => setHistoryFilter({ ...historyFilter, favorites: e.target.checked })}
                className="mr-2"
              />
              <span className="text-gray-300">只看收藏</span>
            </label>
          </div>
          <div>
            <button
              onClick={loadHistory}
              className="flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
            >
              <RefreshCw className="w-4 h-4 mr-2" />
              刷新
            </button>
          </div>
        </div>
      </div>

      {/* History List */}
      <div className="space-y-4">
        {history.map(item => (
          <div key={item.id} className="bg-gray-900 border border-gray-800 rounded-xl p-6">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <div className="flex items-center space-x-3 mb-3">
                  <span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                    {item.request.type}
                  </span>
                  <span className="text-sm text-gray-400">{item.created_at}</span>
                  <span className="text-sm text-gray-400">{item.content.length} 字</span>
                </div>

                <div className="text-gray-100 mb-3">
                  <strong>主题:</strong> {item.request.topic}
                </div>

                <div className="text-gray-300 leading-relaxed line-clamp-3">{item.content}</div>
              </div>

              <div className="flex items-center space-x-2 ml-4">
                <button
                  onClick={() => handleToggleFavorite(item.id)}
                  className={`p-2 rounded-lg transition-colors ${
                    item.is_favorite
                      ? 'text-red-500 hover:text-red-400'
                      : 'text-gray-500 hover:text-gray-400'
                  }`}
                >
                  <Heart className="w-4 h-4" fill={item.is_favorite ? 'currentColor' : 'none'} />
                </button>
                <button
                  onClick={() => handleCopyContent(item.content)}
                  className="p-2 text-gray-500 hover:text-gray-400 rounded-lg transition-colors"
                >
                  <Copy className="w-4 h-4" />
                </button>
                <button
                  onClick={() => handleDeleteHistory(item.id)}
                  className="p-2 text-red-500 hover:text-red-400 rounded-lg transition-colors"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  const renderTemplatesTab = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-xl font-semibold text-gray-100">文案模板</h2>
        <button className="flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
          <PlusCircle className="w-4 h-4 mr-2" />
          创建模板
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {templates.map(template => (
          <div key={template.id} className="bg-gray-900 border border-gray-800 rounded-xl p-6">
            <div className="flex items-start justify-between mb-4">
              <div>
                <h3 className="text-lg font-semibold text-gray-100 mb-2">{template.name}</h3>
                <span className="px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                  {template.type}
                </span>
              </div>
            </div>

            <p className="text-gray-300 text-sm mb-4 line-clamp-2">{template.description}</p>

            <div className="flex items-center justify-between">
              <span className="text-xs text-gray-500">{template.variables.length} 个变量</span>
              <button className="text-blue-500 hover:text-blue-400 text-sm">使用模板</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="min-h-screen bg-black text-white p-6">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-100 mb-2">文案生成</h1>
          <p className="text-gray-400">AI 驱动的智能文案创作工具</p>
        </div>

        {/* Stats Cards */}
        {stats && (
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-400 mb-1">总生成数</p>
                  <p className="text-2xl font-bold text-gray-100">{stats.total_generated}</p>
                </div>
                <FileText className="w-8 h-8 text-blue-500" />
              </div>
            </div>

            <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-400 mb-1">今日生成</p>
                  <p className="text-2xl font-bold text-gray-100">{stats.today_generated}</p>
                </div>
                <TrendingUp className="w-8 h-8 text-green-500" />
              </div>
            </div>

            <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-400 mb-1">本周生成</p>
                  <p className="text-2xl font-bold text-gray-100">{stats.week_generated}</p>
                </div>
                <Clock className="w-8 h-8 text-yellow-500" />
              </div>
            </div>

            <div className="bg-gray-900 border border-gray-800 rounded-xl p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-400 mb-1">平均字数</p>
                  <p className="text-2xl font-bold text-gray-100">{stats.avg_word_count}</p>
                </div>
                <FileText className="w-8 h-8 text-purple-500" />
              </div>
            </div>
          </div>
        )}

        {/* Tabs */}
        <div className="mb-8">
          <nav className="flex space-x-8">
            {[
              { id: 'generate', label: '生成文案', icon: PlusCircle },
              { id: 'history', label: '历史记录', icon: Clock },
              { id: 'templates', label: '模板管理', icon: FileText },
            ].map(({ id, label, icon: Icon }) => (
              <button
                key={id}
                onClick={() => setActiveTab(id as 'generate' | 'history' | 'templates')}
                className={`flex items-center px-6 py-3 rounded-lg font-medium transition-colors ${
                  activeTab === id
                    ? 'bg-blue-600 text-white'
                    : 'text-gray-400 hover:text-gray-300 hover:bg-gray-800'
                }`}
              >
                <Icon className="w-5 h-5 mr-2" />
                {label}
              </button>
            ))}
          </nav>
        </div>

        {/* Tab Content */}
        {activeTab === 'generate' && renderGenerateTab()}
        {activeTab === 'history' && renderHistoryTab()}
        {activeTab === 'templates' && renderTemplatesTab()}
      </div>

      {/* Create Account Modal */}
      {showCreateAccountModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-gray-900 border border-gray-800 rounded-xl p-6 w-full max-w-md mx-4">
            <h3 className="text-lg font-semibold text-gray-100 mb-4">创建自媒体账号</h3>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">账号名称</label>
                <input
                  type="text"
                  value={createAccountForm.name}
                  onChange={e =>
                    setCreateAccountForm({ ...createAccountForm, name: e.target.value })
                  }
                  placeholder="输入账号名称"
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">平台类型</label>
                <select
                  value={createAccountForm.platform}
                  onChange={e =>
                    setCreateAccountForm({
                      ...createAccountForm,
                      platform: e.target.value as SocialPlatform,
                    })
                  }
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  {platformOptions.map(option => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">描述 (可选)</label>
                <textarea
                  value={createAccountForm.description || ''}
                  onChange={e =>
                    setCreateAccountForm({ ...createAccountForm, description: e.target.value })
                  }
                  placeholder="简要描述这个账号..."
                  rows={3}
                  className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                />
              </div>
            </div>

            <div className="flex justify-end space-x-3 mt-6">
              <button
                onClick={() => setShowCreateAccountModal(false)}
                className="cursor-pointer px-4 py-2 text-gray-400 hover:text-gray-300 transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleCreateAccount}
                disabled={!createAccountForm.name.trim()}
                className="cursor-pointer px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TextGeneration;
